package com.ruoyi.business.controller;

import cn.hutool.core.lang.UUID;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.business.config.AliPayConfig;
import com.ruoyi.business.entity.Orders;
import com.ruoyi.business.entity.TotalOrder;
import com.ruoyi.business.service.FrontOrdersService;
import com.ruoyi.business.service.FrontTotalOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 13507
 */
@RestController
@RequestMapping("/business/appAlipay")
public class AppAliPayController {
    private static final String GATEWAY_URL = "https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    private static final String FORMAT= "JSON";
    private static final String CHARSET = "UTF-8";
    private static final String SIGN_TYPE = "RSA2";

    @Autowired
    private FrontTotalOrderService totalOrderService;


    @Autowired
    private FrontOrdersService ordersService;

    @Resource
    private AliPayConfig alipayConfig;

//    @Resource
//    private OrderBackService orderBackService;




    @PostMapping("/pay")
    public String pay(@RequestBody PayParam payParam) {
        System.out.println("app 入口 ====== " +  payParam);
        // 根据传入的支付参数，生成支付宝订单信息
        String orderInfo = generateOrderInfo(payParam.getAmount(), payParam.getSubject(), payParam.getBody(),payParam.getOrderId());

        // 返回支付宝订单信息给前端
        return orderInfo;
    }

    private String generateOrderInfo(double amount, String subject, String body,Long orderId) {
        System.out.println("GATEWAY_URL" + GATEWAY_URL);
        System.out.println(" alipayConfig.getAppPrivateKey() " + alipayConfig.getAppPrivateKey());
        System.out.println("alipayConfig.getAlipayPublicKey()" + alipayConfig.getAlipayPublicKey());


        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL,alipayConfig.getAppId(),
                alipayConfig.getAppPrivateKey(),FORMAT,CHARSET,alipayConfig.getAlipayPublicKey(),SIGN_TYPE);

    /*    AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL,alipayConfig.getAppId(),
                alipayConfig.getAppPrivateKey(),FORMAT,CHARSET,alipayConfig.getAlipayPublicKey(),SIGN_TYPE);*/

        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
        request.setNotifyUrl(alipayConfig.getNotifyUrl());

        AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
        model.setOutTradeNo(String.valueOf(orderId)); // 商户订单号
        model.setSubject(subject); // 商品名称
        model.setBody(body); // 商品描述
        model.setTotalAmount(String.valueOf(amount)); // 支付金额
        model.setProductCode("QUICK_MSECURITY_PAY");

        request.setBizModel(model);

        try {
            AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
            return response.getBody(); // 返回支付宝订单信息
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return null;
        }
    }

    @PostMapping("/notify")
    public String notify(HttpServletRequest request) {
        System.out.println("app 出口 ======== ");
        Map<String, String[]> parameterMap = request.getParameterMap();
        Map<String, String> paramMap = new HashMap<>();
        for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
            paramMap.put(entry.getKey(), entry.getValue()[0]);
        }
        String outTradeNo = paramMap.get("out_trade_no");
        String gmtPayment = paramMap.get("gmt_payment");
        String alipayTradeNo = paramMap.get("trade_no");
        try {
            boolean verifyResult = AlipaySignature.rsaCheckV1(paramMap, alipayConfig.getAlipayPublicKey(), CHARSET, SIGN_TYPE);
            if (verifyResult) {
                // 验证成功，处理支付结果
                String tradeStatus = paramMap.get("trade_status");
                if ("TRADE_SUCCESS".equals(tradeStatus) || "TRADE_FINISHED".equals(tradeStatus)) {


                    /**
                     * 处理订单
                     */
                    LambdaQueryWrapper<TotalOrder> l1=new LambdaQueryWrapper<>();
                    l1.eq(TotalOrder::getUuidOrderId,outTradeNo);
                    List<TotalOrder> totalOrderList = totalOrderService.list(l1);

                    //找到需要修改状态的订单 从TotalOrder找到需要更改的订单
                    for (TotalOrder totalOrder : totalOrderList) {
                        Long orderId = totalOrder.getOrderId();

                        Orders orders = ordersService.getById(orderId);

                        //修改订单状态
                        orders.setOrderType(11);
                        totalOrder.setTradeNo(alipayTradeNo);
                        totalOrderService.updateById(totalOrder);
                        ordersService.updateById(orders);
                    }
                    // 支付成功，更新订单状态等操作
                    // ...
                    System.out.println("交易名称: " + paramMap.get("subject"));
                    System.out.println("交易状态: " + paramMap.get("trade_status"));
                    System.out.println("支付宝交易凭证号: " + paramMap.get("trade_no"));
                    System.out.println("商户订单号: " + paramMap.get("out_trade_no"));
                    System.out.println("交易金额: " + paramMap.get("total_amount"));
                    System.out.println("买家在支付宝唯一id: " + paramMap.get("buyer_id"));
                    System.out.println("买家付款时间: " + paramMap.get("gmt_payment"));
                    System.out.println("买家付款金额: " + paramMap.get("buyer_pay_amount"));
                }

                return "success";
            } else {
                // 验证失败
                return "fail";
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return "fail";
        }
    }
}
